package com.jd.webapp.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jd.cms.pojo.ContentCategory;
import com.jd.cms.service.ContentCategoryService;
import com.jd.common.convention.TTResult;
import com.jd.webapp.pojo.EasyUITreeNode;


@Controller
public class ContentCategoryController {
	@Autowired
	private ContentCategoryService contentCategoryService;
	
	@RequestMapping("/content/category/list")
	public @ResponseBody Object getContentCategory(@RequestParam(defaultValue="0")long id){
		try {
			List<EasyUITreeNode> nodes = new ArrayList<EasyUITreeNode>();
			List<ContentCategory> contentCategorys = contentCategoryService.getContentCategory(id);
			for(ContentCategory ccat: contentCategorys){
				nodes.add(contentCategoryToEasyUITreeNode(ccat));
			}
			return nodes;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping("/content/category/create")
	public @ResponseBody Object addContentCategory(ContentCategory contentCategory){
		try {
			contentCategoryService.tx_addContentCategory(contentCategory);
			return TTResult.ok(contentCategory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TTResult.fail();
	}
	
	//将内容分类转化成Easyui-tree-node对象
	private EasyUITreeNode contentCategoryToEasyUITreeNode(ContentCategory contentCategory){
		EasyUITreeNode node = new EasyUITreeNode();
		node.setId(contentCategory.getId());
		node.setText(contentCategory.getName());
		node.setState(contentCategory.getIsParent()?"closed":"open");
		return node;
	}
}
